package Test.SemaphoreDemo;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @author handsomePot
 * @date 2022/1/10 22:41
 */
public class BaseDemo {

    public static void main(String[] args) throws InterruptedException {

        Semaphore semaphore = new Semaphore(2);


        new Thread(() -> {
            try {
                semaphore.acquire();
                System.out.println("线程A：获取信号量成功");
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                semaphore.release();
            }
        }).start();


        TimeUnit.MILLISECONDS.sleep(200);

        new Thread(() -> {
            try {
                semaphore.acquire(2);
                System.out.println("线程B：获取信号量成功");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                semaphore.release(2);
            }
        }).start();


        new Thread(() -> {
            try {
                semaphore.acquire();
                System.out.println("线程C：获取信号量成功");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                semaphore.release();
            }
        }).start();


    }

}
